package com.lagou.edu.controller;

import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.dao.LagouTokenDao;
import com.lagou.edu.dao.LagouUserDao;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.pojo.LagouUser;
import com.lagou.edu.utils.MyDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.data.domain.Example;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/api/user")
@RestController
public class UserController {

    @Autowired
    private LagouTokenDao lagouTokenDao;

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Autowired
    private LagouUserDao lagouUserDao;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    @RequestMapping("/saveByLagouToken")
    public LagouToken saveByLagouToken(LagouToken lagouToken){
        System.out.println(lagouToken);
        return lagouTokenDao.save(lagouToken);
    }

    /**
     * 注册接口,true 成功, false 失败
     * @param email
     * @param password
     * @param code
     * @return
     */
    @RequestMapping("/register/{email}/{password}/{code}")
    public Map<String,Object> register(@PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code,HttpServletResponse response,HttpServletRequest request) throws ParseException {
        Map<String,Object> rs = new HashMap<>();
        rs.put("code",0);
        rs.put("status",true);
        rs.put("msg","注册成功");
        // 传入的参数校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(code)){
            rs.put("code",400);
            rs.put("status",false);
            rs.put("msg","email、password和code为必填项.");
            return rs;
        }
        // 验证code值是否在且未过期
        LagouAuthCode authCode = lagouAuthCodeDao.getOneByCode(code);
        if (authCode == null || authCode.getId() == null){
            rs.put("code",401);
            rs.put("status",false);
            rs.put("msg","code不正确");
            return rs;
        }
        if (MyDateTime.dateToStamp(authCode.getExpiretime()) - System.currentTimeMillis() <= 0){
            rs.put("code",402);
            rs.put("status",false);
            rs.put("msg","code已失效");
            return rs;
        }
        // email是否已经注册过
        LagouUser lagouUser1 = lagouUserDao.getByUsername(email);
        if (lagouUser1 != null && lagouUser1.getId() > 0){
            rs.put("code",501);
            rs.put("status",false);
            rs.put("msg","该email已经注册过.");
            return rs;
        }
        // 添加用户信息到表中
        LagouUser lagouUser = new LagouUser();
        lagouUser.setUsername(email);
        lagouUser.setPassword(password);
        lagouUser.setCreatetime(MyDateTime.getCurrentDateTime());
        lagouUser.setUpdatetime(MyDateTime.getCurrentDateTime());
        lagouUserDao.save(lagouUser);
        // 生成token令牌
        String token = UUID.randomUUID().toString();
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(token);
        lagouTokenDao.save(lagouToken);
        Cookie cookie = new Cookie("token",token);
        response.addCookie(cookie);
        return rs;
    }


    /**
     * 是否已注册,根据邮箱判断,true代表已经注册过,false代表尚未注册过
     * @param email
     * @return
     */
    @RequestMapping("isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email){
        LagouUser lagouUser = lagouUserDao.getByUsername(email);
        if (lagouUser != null && lagouUser.getId() > 0){
            return false;
        }
        return true;
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     * @param email
     * @param password
     * @return
     */
    @RequestMapping("/login/{email}/{password}")
    public Map<String,Object> login(@PathVariable("email") String email,
                                    @PathVariable("password") String password, HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> rs = new HashMap<>();
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)){
            rs.put("code",400);
            rs.put("status","fail");
            rs.put("token","");
            rs.put("msg","email和password不能为空");
            return rs;
        }
        // 验证用户密码是否正确
        LagouUser lagouUser = lagouUserDao.getByUsernameAndPassword(email, password);
        if (lagouUser == null || lagouUser.getId() == null){
            rs.put("code",402);
            rs.put("status","fail");
            rs.put("msg","用户名或者密码错误!");
            return rs;
        }
        // 先将历史令牌删除
        LagouToken lagouToken2 = new LagouToken();
        lagouToken2.setEmail(email);
        lagouTokenDao.delete(lagouToken2);
        // 生成令牌存储一下
        String token = UUID.randomUUID().toString();
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(token);
        LagouToken save = lagouTokenDao.save(lagouToken);
        if (save.getId() == null){
            rs.put("code",401);
            rs.put("msg","保存令牌失败");
            return  rs;
        }
        rs.put("code",0);
        rs.put("status","success");
        rs.put("token", token);
        rs.put("msg","登录成功");
        Cookie cookie = new Cookie("token",token);
        cookie.setDomain("www.test.com");
        response.addCookie(cookie);
        return rs;
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     * @param token
     * @return
     */
    @RequestMapping("/info/{token}")
    public Map<String,String> info(@PathVariable("token") String token){
        System.out.println("==============================");
        System.out.println(token);
        System.out.println("------------------------------");
        Map<String,String> rs = new HashMap<>();
        rs.put("status","success");
        rs.put("email","799590989@qq.com");
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo("981800175@qq.com");
        message.setSubject("test");
        message.setText("content");
        javaMailSender.send(message);
        return rs;
    }

}
